<template>
    <section>
        <full-screen-dialog
            title="进行对账"
            v-model="visible"
            :width="1400"
            destroy-on-close
            @closed="$emit('closed')"
        >
            <el-form ref="dialogForm" label-width="100px">
                <el-form inline label-width="49px" :model="entityObj" style="margin-top: 5px">
                    <el-form-item label="对账日期" label-width="100px">
                        <el-date-picker
                            style="width: 400px"
                            v-model="entityObj.storageOrderAccountTimes"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            range-separator="-"
                            unlink-panels="true"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :default-time="defaultTime"
                            required
                        />
                    </el-form-item>
                    <el-form-item label="供应商" label-width="100px">
                        <el-input
                            placeholder="---请输入供应商名称---"
                            v-model="entityObj.supplierName"
                            style="width: 300px"
                            disabled
                        />
                    </el-form-item>
                    <br />
                    <el-form-item label-width="100px" label="附件上传">
                        <sc-upload-file
                            v-model="entityObj.accountFile"
                            :objName="'Supply/giveOrder'"
                            draggable
                            :uploadType="'OSS'"
                            :bucketName="'jtmc'"
                            :limit="1"
                        />
                    </el-form-item>
                </el-form>
                <div style="margin-bottom: 10px;">
                    <el-button type="primary" @click="opBatchSuccess()">批量对账正确</el-button>
                    <el-button type="primary" @click="choiceStorageOrder()">选择采购单</el-button>
                    <el-button type="primary" @click="opDelSelect()">批量删除</el-button>
                </div>
                <el-form inline label-width="49px" style="margin-top: 5px">
                    <el-form-item label="物料编号" label-width="80px">
                        <el-input
                            placeholder="---请输入编号---"
                            v-model="queryList.materialCode"
                            style="width: 160px"
                        />
                    </el-form-item>
                    <el-form-item label="物料名称" label-width="80px">
                        <el-input
                            placeholder="---请输入名称---"
                            v-model="queryList.materialName"
                            style="width: 160px"
                        />
                    </el-form-item>
                    <el-form-item label="物料规格" label-width="80px">
                        <el-input
                            placeholder="---请输入规格---"
                            v-model="queryList.materialSpecs"
                            style="width: 160px"
                        />
                    </el-form-item>
                    <el-form-item label="关联单号" label-width="80px">
                        <el-input
                            placeholder="---请输入关联单号---"
                            v-model="queryList.purchaseOrderCode"
                            style="width: 160px"
                        />
                    </el-form-item>
                    <el-form-item label-width="80px">
                        <el-button
                            :icon="Search"
                             
                            type="primary"
                            @click="handleSearch"
                        >查询</el-button>
                        <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                    </el-form-item>
                </el-form>
                <scTable
                    :data="listData"
                    :border="true"
                    style="width: 100%"
                    show-summary
                    :summary-method="getSummaries"
                    @selection-change="selectionChange"
                    :hidePagination="true"
                >
                    <el-table-column type="selection" width="50"></el-table-column>
                    <el-table-column label="序号" type="index" width="60"></el-table-column>
                    <el-table-column label="对账状态" prop="statusDesc" width="100">
                        <template #default="scope">
                            <span
                                v-if="this.orgType==1 && scope.row.wineStatus==1"
                            >{{scope.row.wineStatusDesc}}</span>
                            <span
                                v-else-if="this.orgType==3 && scope.row.supplierStatus==1"
                            >{{scope.row.supplierStatusDesc}}</span>
                            <span v-else>{{scope.row.statusDesc}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="业务日期" prop="applyDate" width="130">
                        <template
                            #default="scope"
                        >{{ scope.row.applyDate?.length>10? scope.row.applyDate?.slice(0, 10):scope.row.applyDate}}</template>
                    </el-table-column>
                    <el-table-column label="物料名称" prop="materialName" width="250"></el-table-column>
                    <el-table-column label="规格型号" prop="materialSpecs" width="100"></el-table-column>

                    <el-table-column label="单位" prop="unitName" width="80"></el-table-column>

                    <el-table-column label="结算数量" prop="qty" width="90"></el-table-column>
                    <el-table-column label="结算单价" prop="price" width="90"></el-table-column>
                    <el-table-column label="结算金额" prop="totalAmount" width="90"></el-table-column>

                    <!-- <el-table-column label="单据日期" prop="storageOrderTime" width="180"></el-table-column> -->
                    <el-table-column label="单据编号" prop="storageOrderCode" width="200"></el-table-column>
                    <!-- 	<el-table-column label="下单时间" prop="storageOrderTime" width="200"></el-table-column> -->
                    <el-table-column label="制单人" prop="documentsUser" width="100"></el-table-column>
                    <el-table-column label="对账人" prop="reviewed" width="100"></el-table-column>
                    <el-table-column label="要货单位" prop="storeName" width="200"></el-table-column>
                    <!-- <el-table-column label="期望到货时间" prop="" width="200"></el-table-column> -->
                    <el-table-column label="关联单号" prop="purchaseOrderCode" width="200"></el-table-column>
                    <el-table-column label="类型" prop="storageOrderTypeDesc" width="200"></el-table-column>
                    <el-table-column label="物料编码" prop="materialCode" width="100"></el-table-column>

                    <!-- <el-table-column prop="purchaseQty" width="100">
						<template #header>
							<el-popover placement="top-start" :width="200" trigger="hover" content="发货数量,退货数量,空瓶有效数量">
								<template #reference>
									数量
								</template>
							</el-popover>
						</template>
					</el-table-column>
					<el-table-column label="差异" prop="diffQty" width="100"></el-table-column>
					
					<el-table-column label="单价" prop="purchasePrice" width="100"></el-table-column>
                    <el-table-column label="差异" prop="diffPrice" width="100"></el-table-column>-->
                    <el-table-column label="备注" prop="remarks" width="100"></el-table-column>
                    <el-table-column label="操作" fixed="right" align="center" width="200">
                        <template #default="scope">
                            <el-button-group>
                                <span>
                                    <el-button
                                        text
                                        type="primary"
                                        size="small"
                                        @click="openDel(scope.row, scope.$index)"
                                    >删除</el-button>
                                </span>
                                <!-- 酒业 -->
                                <span v-if="this.orgType==1 && scope.row.wineStatus!=1">
                                    <el-button
                                        text
                                        type="primary"
                                        size="small"
                                        @click="opSuccess(scope.row, scope.$index)"
                                    >对账正确</el-button>
                                </span>
                                <span>
                                    <el-button
                                        v-if="this.orgType==1 && scope.row.wineStatus!=1"
                                        text
                                        type="primary"
                                        size="small"
                                        @click="opCheck(scope.row, scope.$index)"
                                    >核对</el-button>
                                </span>
                                <!-- 供应商 -->
                                <span v-if="this.orgType==3 && scope.row.supplierStatus==0">
                                    <el-button
                                        text
                                        type="primary"
                                        size="small"
                                        @click="opSuccess(scope.row, scope.$index)"
                                    >对账正确</el-button>
                                </span>
                            </el-button-group>
                        </template>
                    </el-table-column>
                </scTable>
            </el-form>
            <template #footer>
                <div style="text-align: center;">
                    <el-button @click="visible = false">关 闭</el-button>
                    <el-button type="primary" @click="submit()">保 存</el-button>
                </div>
            </template>
        </full-screen-dialog>
    </section>
    <check-dialog
        v-if="dialogCheck"
        ref="checkDialog"
        @fatherMethod="opBindData"
        @success="handleSaveSuccess"
        @closed="dialogCheck = false"
    ></check-dialog>

    <receive-choice
        v-if="visibleReceiveChoice"
        ref="receiveChoiceObj"
        @fatherMethod="opBindData"
        @checkTable="checkTable"
        @success="handleSaveSuccess"
        @closed="visibleReceiveChoice = false"
    ></receive-choice>
    <!-- 要货价格修改 -->
    <update-price-dialog
        v-if="dialogUpdatePrice"
        ref="updatePriceDialog"
        @fatherMethod="opBindData"
        @success="handleSaveSuccess"
        @closed="dialogUpdatePrice = false"
    ></update-price-dialog>
</template>

<script>
import tool from "@/utils/tool";
import checkDialog from "./check";
import receiveChoice from "../receiveChoice";
import updatePriceDialog from "../../../purchase/order/order/updatePrice.vue";

export default {
    components: {
        checkDialog,
        receiveChoice,
        updatePriceDialog,
    },
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Check",
            titleMap: {
                Check: "核对",
                Show: "查看",
            },
            visibleReceiveChoice: false,
            dialogUpdatePrice:false,
            visible: false,
            orgType: "",
            entityObj: {},
            rules: {},
            listData: [],
            delIds: [],
            dialogCheck: false,
            selectionRows: [],
            queryList: {},
            initItems: [], // 初始化存储
            defaultTime: [
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ],
        };
    },
    computed: {
        isSelectable() {
            return (row) => {
                // 根据 orgType 和 row 状态判断是否可以选择
                if (this.orgType == 1) {
                    return row.wineStatus == 0;
                } else if (this.orgType == 3) {
                    return row.supplierStatus == 0;
                }
                return false;
            };
        },
    },
    methods: {
        //显示=
        open() {
            this.visible = true;
            return this;
        },
        //表格选择后回调事件
        selectionChange(selection) {
            console.log(11);

            this.selectionRows = selection;
            console.log(this.selectionRows);
        },
        //表单注入数据
        async setData(data) {
            console.log("开始对账", data);
            var arr = [];
            arr.push(data.storageOrderAccountId);
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "storage-order-account/items",
                    {
                        storageOrderAccountIds: arr,
                    }
                );
                debugger;
                if (returnValue.status == 200) {
                    this.entityObj = data;

                    var array = [];
                    array.push(data.accountStartDate);
                    array.push(data.accountEndDate);
                    this.entityObj.storageOrderAccountTimes = array;
                    this.entityObj.purchaseUnityId = data.purchaseUnityId;
                    this.entityObj.supplierId = data.supplierId;
                    this.listData = returnValue.response;
                    this.initItems = returnValue.response;

                    console.log("entityObj", this.entityObj);
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
            // try {

            // 	this.entityObj = row
            // 	var array=[];
            // 	array.push(row.accountStartDate);
            // 	array.push(row.accountEndDate);

            // 	this.entityObj.storageOrderAccountTimes=array
            // 	this.listData = data

            // } catch (error) {
            // 	this.loading = false;
            // 	return false;
            // }
        },
        async getItems() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "storage-order-account/items",
                    {
                        storageOrderAccountIds: [
                            this.entityObj.storageOrderAccountId,
                        ],
                    }
                );
                debugger;
                if (returnValue.status == 200) {
                    this.listData = returnValue.response;
                    this.initItems = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        resetSearch() {
            this.queryList = {};
        },
        handleSearch() {
            var items = this.initItems;
            if (this.queryList.materialCode) {
                items = items.filter((item) => {
                    return item.materialCode.includes(
                        this.queryList.materialCode
                    );
                });
            }

            if (this.queryList.materialName) {
                items = items.filter((item) => {
                    return item.materialName.includes(
                        this.queryList.materialName
                    );
                });
            }
            if (this.queryList.materialSpecs) {
                items = items.filter((item) => {
                    return item.materialSpecs.includes(
                        this.queryList.materialSpecs
                    );
                });
            }
            if (this.queryList.purchaseOrderCode) {
                items = items.filter((item) => {
                    return item.purchaseOrderCode.includes(
                        this.queryList.purchaseOrderCode
                    );
                });
            }
            this.listData = items;
            console.log(items);
        },
        //核对
        async opCheck(row) {
            switch(row.storageOrderType){
                case 0:
                    this.dialogUpdatePrice = true;
                    this.$nextTick(() => {
                        this.$refs.updatePriceDialog.setData(row);
                        this.$refs.updatePriceDialog.open("updatePrice");
                    });
                    break;
                default:
                    this.dialogCheck = true;
                    this.$nextTick(() => {
                        this.$refs.checkDialog.setData(row);
                        this.$refs.checkDialog.open("Check");
                    });
                    break;
            }
        },
        //对账正确
        async opSuccess(row) {
            this.$confirm("确认对账正确？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    try {
                        let arr = [];
                        arr.push(row.storageOrderId);
                        this.$API.auth.PostProcessApi.post(
                            "storage-order-account/checkSuccess",
                            {
                                storageOrderIds: arr,
                            }
                        ).then((returnValue) => {
                            if (returnValue.status == 200) {
                                this.$message.success("操作成功");
                                this.setData(this.entityObj);
                            } else {
                                this.$message.error(
                                    "操作失败:" + returnValue.msg
                                );
                            }
                        });
                    } catch (error) {
                        this.loading = false;
                        return false;
                    }
                })
                .catch(() => {
                    //取消退出
                });
        },
        // 批量对账正确
        async opBatchSuccess() {
            if (this.selectionRows.length > 0) {
                this.$confirm("确认批量对账正确？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        let arr = [];
                        let set = new Set();
                        this.selectionRows.forEach((item) => {
                            if (!set.has(item.storageOrderId)) {
                                set.add(item.storageOrderId);
                                arr.push(item.storageOrderId);
                            }
                        });
                        try {
                            this.$API.auth.PostProcessApi.post(
                                "storage-order-account/checkSuccess",
                                {
                                    storageOrderIds: arr,
                                }
                            ).then((returnValue) => {
                                if (returnValue.status == 200) {
                                    this.$message.success("操作成功");
                                    this.visible = false;
                                } else {
                                    this.$message.error(
                                        "操作失败:" + returnValue.msg
                                    );
                                }
                            });
                        } catch (error) {
                            this.loading = false;
                            return false;
                        }
                    })
                    .catch(() => {
                        //取消退出
                    });
            } else {
                this.$message.error("请选择要打印的数据");
            }
        },
        //保存
        async submit() {
            console.log(111);
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "storage-order-account/update",
                    this.entityObj
                );
                if (returnValue.status == 200) {
                    this.$message.success(returnValue.msg);
                    this.$emit("fatherMethod");
                    this.visible = false;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                this.$message.error(error.message);
                return false;
            }

            // let obj = {}
            // obj.storageOrderId = this.entityObj.storageOrderId
            // obj.price = this.entityObj.price
            // obj.qty = this.entityObj.qty
            // obj.totalAmount = this.entityObj.totalAmount
            // obj.remarks = this.entityObj.remarks

            // const returnValue = await this.$API.auth.PostProcessApi.post(
            //     "storage-order/check",
            //     obj
            // );
            // if (returnValue.status == 200) {
            // 	this.$message.success(returnValue.msg);
            // 	this.$emit("fatherMethod");
            // 	this.visible = false;
            // } else {
            //     this.$message.error("操作失败:" + returnValue.msg);
            // }
        },

        // 提示标签
        renderHeaderMethods(h, { column }) {
            let colVal = column.property;
            let msg = "";
            if (colVal === "cameraX") {
                msg = "双击对应相机坐标X参数将进入编辑模式,";
            } else if (colVal === "cameraY") {
                msg = "双击对应相机坐标Y参数将进入编辑模式,";
            } else if (colVal === "cameraZ") {
                msg = "双击对应相机坐标Z参数将进入编辑模式,";
            }
            return h("div", [
                h("span", column.label),
                h(
                    "el-tooltip",
                    {
                        undefined,
                        props: {
                            undefined,
                            effect: "dark",
                            placement: "top",
                            content: "",
                        },
                    },
                    [
                        h(
                            "div",
                            {
                                slot: "content",
                            },
                            [msg, h("br"), "编辑完成后点击空白处完成编辑."]
                        ),
                        h("i", {
                            undefined,
                            class: "el-icon-question",
                            style: "color:#409eff;",
                        }),
                    ]
                ),
            ]);
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = data.map((item) =>
                    Number(item[column.property])
                );

                if (column.property == "qty") {
                    var qtySum = 0;
                    this.selectionRows.map((selectItem) => {
                        qtySum += selectItem.qty;
                    });
                    sums[index] = qtySum;
                }
                if (column.property == "price") {
                    var PriceSum = 0;
                    this.selectionRows.map((selectItem) => {
                        PriceSum += selectItem.price;
                    });
                    sums[index] = PriceSum;
                }

                if (column.property == "totalAmount") {
                    let totalAmountSum = 0;
                    this.selectionRows.map((selectItem) => {
                        totalAmountSum += selectItem.totalAmount;
                    });
                    sums[index] = totalAmountSum;
                }
            });
            return sums;
        },
        //选择入库单
        choiceStorageOrder() {
            // if (
            //     !this.entityObj.storageOrderAccountTimes ||
            //     this.entityObj.storageOrderAccountTimes.length == 0
            // ) {
            //     this.$message.error("请选择对账时间");
            //     return;
            // }
            if (!this.entityObj.purchaseUnityId) {
                this.$message.error("请选择对账单位");
                return;
            }

            if (!this.entityObj.supplierId) {
                this.$message.error("请选择对账单位");
                return;
            }

            const notStorageOrderIds = this.listData.map(
                (p) => p.storageOrderId
            );

            this.visibleReceiveChoice = true;
            this.$nextTick(() => {
                this.$refs.receiveChoiceObj.initData(
                    this.entityObj.purchaseUnityId,
                    null,
                    //this.entityObj.storageOrderAccountTimes,
                    this.entityObj.supplierId,
                    notStorageOrderIds
                );
            });
        },
        //选择入库单
        async checkTable(data) {
            console.log("selected", data);
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "storage-order-account/add-account-item",
                    {
                        storageOrderAccountId:
                            this.entityObj.storageOrderAccountId,
                        storageOrderAccountItems: data,
                    }
                );
                if (returnValue.status == 200) {
                    await this.getItems();
                    this.$message.success("操作成功");
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        //删除
        openDel(row, index) {
            try {
                this.$API.auth.PostProcessApi.post(
                    "storage-order-account/del-account-item",
                    {
                        storageOrderAccountId:
                            this.entityObj.storageOrderAccountId,
                        storageOrderAccountItems: [
                            {
                                storageOrderAccountItemId:
                                    row.storageOrderAccountItemId,
                            },
                        ],
                    }
                ).then((returnValue) => {
                    if (returnValue.status == 200) {
                        this.initItems = this.initItems.filter(
                            (item) => item.storageOrderId != row.storageOrderId
                        );
                        this.handleSearch();
                        this.$message.success("操作成功");
                    } else {
                        this.$message.error("操作失败:" + returnValue.msg);
                    }
                });
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        // 批量选择删除
        opDelSelect() {
            if (this.selectionRows.length < 1) {
                this.$message.error("请选择要删除的数据");
                return;
            }

            let ids = [];
            this.selectionRows.forEach((item) => {
                ids.push(item.storageOrderId);
            });

            try {
                this.$API.auth.PostProcessApi.post(
                    "storage-order-account/del-account-item",
                    {
                        storageOrderAccountId:
                            this.entityObj.storageOrderAccountId,
                        storageOrderAccountItems: this.selectionRows,
                    }
                ).then((returnValue) => {
                    if (returnValue.status == 200) {
                        this.initItems = this.initItems.filter(
                            (item) => !ids.includes(item.storageOrderId)
                        );
                        this.handleSearch();
                        this.$message.success("操作成功");
                    } else {
                        this.$message.error("操作失败:" + returnValue.msg);
                    }
                });
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
    },
    async mounted() {
        this.orgType = tool.data.get("USER_INFO").AccountType;
    },
};
</script>

<style scoped>
</style>
